<template>
  <div>
    <div class="flex flex-wrap">
      <div v-for="(item,index) in selectRows" :key="item.id" class="select-btn">
        <span>{{ item.htmlText }}</span>
        <i class="el-icon-error ml-10" style="cursor: pointer" @click="deleteRow(index)" />
      </div>
      <el-button @click="handleOpen">{{ btnText }}</el-button>
    </div>

    <el-dialog
      :title="btnText"
      :visible.sync="open"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
    >
      <YxhyTableQuery
        :add-page-router="addPageRouter"
        :should-add-button="shouldAddButton"
        :query-params.sync="queryParamsModal"
        :static-query-params="staticQueryParams"
        :query-columns="queryColumns"
        @search="handleQuery"
      />
      <YxhyTableData
        ref="dialogSelectYxhyTableDataRef"
        :columns="columns"
        :data="tableList"
        :loading="loading"
        :max-height="400"
        @changeCurrent="changeCurrent"
        @selectionChange="selectionChange"
      >
        <template #radio>
          <el-table-column label="" align="center" width="60">
            <template slot-scope="scope">
              <el-radio v-model="radioVal" class="radio" :label="scope.row[tableKey]">
                <span />
              </el-radio>
            </template>
          </el-table-column>
        </template>
        <!-- 短剧库-封面图插槽 -->
        <template #cover>
          <el-table-column label="封面" align="center" width="auto">
            <template slot-scope="scope">
              <el-image
                style="width: 50px; height: auto; "
                :src="scope.row.cover"
                :preview-src-list="[scope.row.cover]"
                fit="fill"
              />
            </template>
          </el-table-column>
        </template>
        <!-- 回传配置-回传方式插槽 -->
        <template #adv_report_type>
          <el-table-column label="回传方式" align="center" width="auto">
            <template slot-scope="scope">
              <p class="font-color-td">{{ ADV_REPORT_TYPE[scope.row.adv_report_type] }}</p>
            </template>
          </el-table-column>
        </template>
        <!-- 充值模板配置-充值类型 -->
        <template #template_type_text>
          <el-table-column label="充值类型" align="center" width="auto">
            <template slot-scope="scope">
              <p class="font-color-td">{{ TEMPLATE_TYPE[scope.row.type] }}</p>
            </template>
          </el-table-column>
        </template>
      </YxhyTableData>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryPage.pageNum"
        :limit.sync="queryPage.limit"
        @pagination="init"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleBack">返回</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ADV_REPORT_TYPE } from '@/api/config/channelPostBack.js'
import { TEMPLATE_TYPE } from '@/api/config/template'
export default {
  name: 'YxhyTableDialogSelect',
  props: {
    btnText: {
      type: String,
      default: '选择'
    },
    /**  添加跳转路由  */
    addPageRouter: {
      type: String,
      default: ''
    },
    /**  显示添加按钮  */
    shouldAddButton: {
      type: Boolean,
      default: false
    },
    /** 接口数据表格id健 */
    tableKey: {
      type: String,
      default: ''
    },
    /** 接口数据表格name健 */
    tableName: {
      type: String,
      default: ''
    },
    /** 详情数据源 */
    detailData: {
      type: Object,
      default: () => null
    },
    detailIdKey: {
      type: String,
      default: ''
    },
    tableMode: {
      type: String,
      default: 'radio' // radio=单选模式  selection=多选模式
    },
    columns: {
      // 参考Ds.js定义
      // 配置slot: 'radio' 单选模式
      // 配置type: 'selection' 多选模式
      type: Array,
      default: () => []
    },
    queryParams: {
      type: Object,
      default: () => {
      }
    },
    staticQueryParams: {
      type: Object,
      default: () => {
      }
    },
    queryColumns: {
      type: Array,
      default: () => []
    },
    requestFn: {
      type: Function
    }
  },
  data() {
    return {
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 分页参数
      queryPage: {
        pageNum: 1,
        limit: 10
      },
      open: false,
      loading: false,
      queryParamsModal: {},
      selectRows: [],
      selectRowsTemp: [],
      radioVal: undefined,

      // 回传配置-回传方式
      ADV_REPORT_TYPE,
      // 充值模板配置-充值类型
      TEMPLATE_TYPE
    }
  },
  computed: {
    // 单选模式
    isTableModeRadio() {
      const result = this.$props.columns.some(e => e.slot === 'radio')
      return result
    },
    // 多选模式
    isTableModeSelection() {
      const result = this.$props.columns.some(e => e.type === 'selection')
      return result
    }
  },
  watch: {
    detailData: {
      handler(val) {
        if (val == null) {
          this.selectRows = []
          this.selectRowsTemp = []
          return
        }
        setTimeout(() => {
          // 避免报重复请求
          this.queryParamsModal.test = 1
          this.init()
        }, 300)
      },
      deep: true
    },
    queryParams: {
      // 因为props无法作为响应式数据，:query-params.sync无法绑定，因此转为响应式
      handler(val) {
        this.queryParamsModal = JSON.parse(JSON.stringify(val))
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    async handleOpen() {
      this.open = true
      await this.init()
      this.reverseSelectTableRows()
    },
    handleBack() {
      this.open = false
    },
    async init() {
      this.loading = true
      const res = await this.$props.requestFn({
        ...this.queryPage,
        ...this.queryParamsModal,
        ...this.$props.staticQueryParams
      })
      if (res.data && Array.isArray(res.data)) {
        // 分页版本
        this.tableList = res.data
        this.total = res.total || 0
      } else {
        this.tableList = res
      }

      if (this.$props.detailData != null) {
        this.reviveData()
      }
      this.loading = false
    },
    onReset() {
      this.selectRows = []
      this.selectRowsTemp = []
    },
    // 编辑时，处理数据源
    reviveData() {
      const { tableKey, detailIdKey, detailData } = this.$props
      // 得到详情数据的id数组
      const ids = detailData[detailIdKey].toString()
      const idArr = ids.split(',')
      console.log('-----------处理开始sta------------')
      console.log('detailData===', detailData)
      console.log('detailIdKey==', detailIdKey)
      console.log('idArr===', idArr)
      console.log('tableList===', this.tableList)
      console.log('-----------处理结束end------------')
      const resultArr = this.tableList.filter(e => {
        const tempId = e[tableKey].toString()
        if (idArr.includes(tempId)) {
          return e
        }
      })
      this.selectRows = resultArr.map(e => {
        return { ...e, htmlText: e[this.$props.tableName] }
      })
    },
    // 根据已选择的数据，反响勾选表格行
    reverseSelectTableRows() {
      this.$nextTick(() => {
        if (this.isTableModeRadio) {
          const [row] = this.selectRows
          this.$refs.dialogSelectYxhyTableDataRef.setCurrentRadioRow(row)
        } else if (this.isTableModeSelection) {
          const { tableKey } = this.$props
          const s_ids = this.selectRows.map(e => e[tableKey])
          const rows = this.tableList.filter(e => s_ids.includes(e[tableKey]))
          this.$refs.dialogSelectYxhyTableDataRef.toggleSelection(rows)
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParamsModal.pageNum = 1
      this.init()
    },
    /** 接收表格单选 */
    changeCurrent(row) {
      if (!row) return

      this.selectRowsTemp = [row]
      this.radioVal = row[this.$props.tableKey]
    },
    /** 接收表格多选 */
    selectionChange(rows) {
      this.selectRowsTemp = rows
    },
    /** 删除已选择 */
    deleteRow(index) {
      this.selectRows.splice(index, 1)
      this.$emit('selectResult', this.selectRows)
    },
    /** 确定按钮操作 */
    handleSubmit() {
      this.open = false
      const newRows = this.selectRowsTemp.map(e => {
        return {
          ...e,
          htmlText: e[this.$props.tableName]
        }
      })
      this.selectRows = newRows

      this.$emit('selectResult', this.selectRows)
      // 清空表格单选
      this.radioVal = undefined
      // 清空表格多选
      this.$refs.dialogSelectYxhyTableDataRef.handleClearSelection()
    }
  }
}
</script>

<style lang="scss" scoped>
.select-btn {
  display: inline-flex;
  align-items: center;
  color: #409eff;
  background: #ecf5ff;
  border-color: #b3d8ff;
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 4px;
  white-space: nowrap;
  line-height: 1;
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
